import { useFormMode } from '@/components/base/Form/mode';
import CodeMirror from 'vue-codemirror6';
import { java } from '@codemirror/lang-java';
import { ElText } from 'element-plus';
import './index.scss';

export const CodeMirrorJava = defineComponent({
  props: {
    code: {
      type: String,
      default: ''
    },
    cmHeight: {
      type: String,
      default: '200px'
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit, expose }) {
    const formMode = useFormMode();
    //  ref
    const codeMirrorRef = ref<any>(null);
    // 代码
    const javaCode = ref(props.code);
    // 语言
    const lang = java();
    // 光标
    const codeCursor = ref(0);

    watch(
      () => [props.code],
      () => {
        if (props.code) {
          javaCode.value = props.code;
        } else {
          javaCode.value = '';
        }
      },
      { immediate: true }
    );

    const getCodeMirrorCursor = () => {
      return codeMirrorRef.value?.getCursor();
    };

    expose({
      getCodeMirrorCursor
    });

    return () => {
      return (
        <div class="w-full h-full">
          {formMode?.mode === 'edit' ? (
            <CodeMirror
              ref={codeMirrorRef}
              modelValue={javaCode.value}
              lang={lang}
              basic={true}
              style={{ height: props.cmHeight }}
              cursor={codeCursor.value}
              class="w-full  min-h-20 bd"
              onUpdate:modelValue={(val: any) => {
                emit('update:modelValue', val);
              }}
            />
          ) : (
            <ElText>{javaCode.value}</ElText>
          )}
        </div>
      );
    };
  }
});
